package com.landeb.shop.huo.act;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.adapter.ActSearchResultRVAdapter;
import com.landeb.shop.huo.bean.BeanSearchResultAct;
import com.landeb.shop.huo.httpRequest.ActSearchResultRequest;
import com.landeb.shop.huo.view.EndlessRecyclerOnScrollListener;
import com.jayfang.dropdownmenu.DropDownMenu;
import com.jayfang.dropdownmenu.OnMenuSelectedListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SearchResultActivity extends BaseActivity implements View.OnClickListener, ActSearchResultRVAdapter.OnItemClickListener {

    private Button btnSearch, btnSwitch;
    private LinearLayout btnBack;
    private int switchFlag = 1;

    private ImageView ivSals, ivPrice;

    private LinearLayout salesLayout, priceLayout;

    private DropDownMenu mDropDownMenu;
    private String[] mMenuHeads = new String[]{"综合"};
    private List<String[]> mMenuItems = new ArrayList<>();
    final String[] select = new String[]{"综合", "新品", "评论"};

    private RecyclerView mRecyclerView;
    private List<BeanSearchResultAct.DataBean.ListBean> mGoods;
    private ActSearchResultRVAdapter mAdapter;
    private LinearLayoutManager mLinearLayoutManager;

    private String mUrl;
    private Retrofit mRetrofit;
    private ActSearchResultRequest mRequest;
    private int mPage = 0;
    private int mLimit = 10;
    private String mKeyword;//关键词
    private String mCid;//商品类别
    private String mOrder;//排序方式
    private String mSort;//排序顺序
    private String mTitle;
    private boolean isLoading = false;
    private boolean hasNextPage = true;

    private int saleFlag = 0;
    private int priceFlag = 0;


    public static final int FLAG_CID = 0;
    public static final int FLAG_KEYWORD = 1;
    public static final int FLAG_TITLE = 2;

    private EndlessRecyclerOnScrollListener mListener;

    public static void toAct(Context context) {

        Intent intent = new Intent(context, SearchResultActivity.class);
        context.startActivity(intent);

    }


    public static void toAct(Context context, int flag, String data) {

        Intent intent = new Intent(context, SearchResultActivity.class);
        intent.putExtra("flag", flag);
        intent.putExtra("data", data);
        context.startActivity(intent);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        if (getIntent().getIntExtra("flag", -1) != -1) {
            int flag = getIntent().getIntExtra("flag", -1);

            if (flag == FLAG_CID) {
                mCid = getIntent().getStringExtra("data");
            } else if (flag == FLAG_KEYWORD) {
                mKeyword = getIntent().getStringExtra("data");
                mTitle = mKeyword;
            } else if (flag == FLAG_TITLE) {
                mTitle = getIntent().getStringExtra("data");
                Log.e("onCreate: ", mTitle);
            }

        }


        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        mRequest = mRetrofit.create(ActSearchResultRequest.class);

        initView();
        initData();
        initEvent();

        loadMore();
    }

    private void initEvent() {


        if (mTitle != null) {
            btnSearch.setText(mTitle);
        }

        btnBack.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
        btnSwitch.setOnClickListener(this);

        mDropDownMenu.setMenuSelectedListener(new OnMenuSelectedListener() {
            @Override
            public void onSelected(View view, int i, int i1) {
                // TODO: 2016/10/24 筛选按钮点击逻辑
                /**
                 * i1是menu item的索引  i是每个item的select索引
                 * */
//                Toast.makeText(SearchResultActivity.this, "i1=" + i1 + "   i=" + i, Toast.LENGTH_SHORT).show();

                if (i1 == 0 && i == 0) {
                    mOrder = "DESC";
                    mSort = null;
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivPrice.setImageResource(R.drawable.icon_select_default);
                    ivSals.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }

                } else if (i1 == 0 && i == 1) {
                    mSort = "ctime";
                    mOrder = "DESC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivPrice.setImageResource(R.drawable.icon_select_default);
                    ivSals.setImageResource(R.drawable.icon_select_default);

                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }

                } else if (i1 == 0 && i == 2) {

                    mSort = "comment";
                    mOrder = "DESC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivPrice.setImageResource(R.drawable.icon_select_default);
                    ivSals.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }

                }


            }
        });


        salesLayout.setOnClickListener(this);
        priceLayout.setOnClickListener(this);

        mAdapter = new ActSearchResultRVAdapter(this, mGoods);
        mAdapter.setOnItemClickListener(this);
        mRecyclerView.setHasFixedSize(true);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mListener = new EndlessRecyclerOnScrollListener(mLinearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                // TODO: 2016/10/25 上拉加载
                loadMore();
                Toast.makeText(SearchResultActivity.this, "正在加载，请稍后", Toast.LENGTH_SHORT).show();
            }
        };
        mRecyclerView.addOnScrollListener(mListener);

    }

    private void initData() {

        mGoods = new ArrayList<>();
//        for (int i = 0; i < 20; i++) {
//            ItemActSearchResultRecyclerView item = new ItemActSearchResultRecyclerView("", "第" + i + "号产品", 0.25 * i, "好评百分百", "");
//            mGoods.add(item);
//        }

    }

    private void initView() {


        btnBack = (LinearLayout) findViewById(R.id.act_searchResult_btn_back);
        btnSearch = (Button) findViewById(R.id.act_searchResult_btn_search);
        btnSwitch = (Button) findViewById(R.id.act_searchResult_btn_switch);

        mDropDownMenu = (DropDownMenu) findViewById(R.id.act_searchResult_menu_dropDown);
        mDropDownMenu.setmMenuCount(1);//Menu的个数
        mDropDownMenu.setmShowCount(6);//Menu展开list数量太多是只显示的个数
        mDropDownMenu.setShowCheck(true);//是否显示展开list的选中项
        mDropDownMenu.setmMenuTitleTextSize(16);//Menu的文字大小
        mDropDownMenu.setmMenuTitleTextColor(Color.BLACK);//Menu的文字颜色
        mDropDownMenu.setmMenuListTextSize(16);//Menu展开list的文字大小
        mDropDownMenu.setmMenuListTextColor(Color.BLACK);//Menu展开list的文字颜色
        mDropDownMenu.setmMenuBackColor(Color.WHITE);//Menu的背景颜色
        mDropDownMenu.setmMenuPressedBackColor(Color.WHITE);//Menu按下的背景颜色
        mDropDownMenu.setmCheckIcon(R.drawable.ico_make);//Menu展开list的勾选图片
        mDropDownMenu.setmUpArrow(R.drawable.arrow_up);//Menu默认状态的箭头
        mDropDownMenu.setmDownArrow(R.drawable.arrow_down);//Menu按下状态的箭头
        mDropDownMenu.setDefaultMenuTitle(mMenuHeads);//默认未选择任何过滤的Menu title
        mDropDownMenu.setShowDivider(false);
        mDropDownMenu.setmMenuListBackColor(getResources().getColor(R.color.white));
        mDropDownMenu.setmMenuListSelectorRes(R.color.white);
        mDropDownMenu.setmArrowMarginTitle(20);
        mMenuItems.add(select);
        mDropDownMenu.setmMenuItems(mMenuItems);


        salesLayout = (LinearLayout) findViewById(R.id.act_searchResult_ll_sales);
        priceLayout = (LinearLayout) findViewById(R.id.act_searchResult_ll_price);

        ivSals = (ImageView) findViewById(R.id.act_searchResult_iv_sales);
        ivPrice = (ImageView) findViewById(R.id.act_searchResult_iv_price);

        mRecyclerView = (RecyclerView) findViewById(R.id.act_searchResult_recyclerView);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.act_searchResult_btn_back:
                // TODO: 2016/10/24 返回键
                onBackPressed();
                break;
            case R.id.act_searchResult_btn_search:
                SearchActivity.toAct(this);
                break;
            case R.id.act_searchResult_btn_switch:
                // TODO: 2016/10/24 视图切换

                SearchActivity.toAct(this);

//                if (switchFlag == 1) {
//                    mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
//                } else {
//                    mRecyclerView.setLayoutManager(mLinearLayoutManager);
//                }
//                switchFlag = (switchFlag + 1) % 2;
                break;

            case R.id.act_searchResult_ll_sales:
                // TODO: 2016/10/24   按销量排序

                Log.e("onClick: ", "+++++isLoadING++++" + isLoading + "hasNextPage" + hasNextPage);

                if (saleFlag == 0) {
//默认销量从高到低
                    mSort = "sale";
                    mOrder = "DESC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivSals.setImageResource(R.drawable.icon_select_top);
                    ivPrice.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();
                    }
                } else {
//从低到高排序
                    mSort = "sale";
                    mOrder = "ASC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivSals.setImageResource(R.drawable.icon_select_bottom);
                    ivPrice.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }
                }

                saleFlag = (saleFlag + 1) % 2;

                break;
            case R.id.act_searchResult_ll_price:
                // TODO: 2016/10/24 按价格排序

                Log.e("onClick: ", "+++++isLoadING++++" + isLoading + "hasNextPage" + hasNextPage);


                if (priceFlag == 0) {
//默认价格从高到低
                    mSort = "price";
                    mOrder = "DESC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivPrice.setImageResource(R.drawable.icon_select_top);
                    ivSals.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }
                } else {
//从价格低到高排序
                    mSort = "price";
                    mOrder = "ASC";
                    hasNextPage = true;
                    mPage = 0;
                    mGoods.clear();
                    loadMore();
                    ivPrice.setImageResource(R.drawable.icon_select_bottom);
                    ivSals.setImageResource(R.drawable.icon_select_default);
                    if (mGoods.size() >= 0) {
                        mRecyclerView.scrollToPosition(0);
                        mListener.resetState();

                    }
                }

                priceFlag = (priceFlag + 1) % 2;

                break;
        }

    }

    @Override
    public void onItemClick(View view, int position) {
        // TODO: 2016/10/24 recyclerView单击回调
//        Toast.makeText(this, position + "", Toast.LENGTH_SHORT).show();

        String id = mGoods.get(position).getGoods_id();
        String title = mGoods.get(position).getName();
        String price = mGoods.get(position).getPrice();

        GoodDetailActivity.toAct(SearchResultActivity.this, id, title, price);

    }


    private void loadMore() {

        mPage++;

        Log.e("loadMore: ", "++++++page++++" + mPage + "hasNextPAGE" + hasNextPage);

        if (!isLoading && hasNextPage) {

            isLoading = true;

            mRequest.getGoods(mPage, mLimit, mKeyword, mCid, mOrder, mSort)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanSearchResultAct>() {
                                   @Override
                                   public void onCompleted() {
                                       isLoading = false;
                                       Log.e("getGoods", "onCompleted: ");

                                   }

                                   @Override
                                   public void onError(Throwable e) {
                                       isLoading = false;
                                       Log.e("getGoods", "onError: ");
                                   }

                                   @Override
                                   public void onNext(BeanSearchResultAct beanSearchResultAct) {

                                       if (beanSearchResultAct.getStatus() == 1) {
//                                           mGoods.clear();
                                           mGoods.addAll(beanSearchResultAct.getData().getList());
                                           mAdapter.notifyDataSetChanged();

                                           if (beanSearchResultAct.getData().getMore() == 0) {
                                               hasNextPage = false;
                                               Toast.makeText(SearchResultActivity.this, "已加载全部", Toast.LENGTH_LONG).show();

                                           }

                                       } else {

                                           Toast.makeText(SearchResultActivity.this, beanSearchResultAct.getInfo(), Toast.LENGTH_SHORT).show();
                                       }
                                   }

                               }
                    );
//        .subscribe(new Subscriber<BeanActHistoryLV>() {
//            @Override
//            public void onCompleted() {
//                isLoading = false;
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                isLoading = false;
//            }
//
//            @Override
//            public void onNext(BeanActHistoryLV beanActHistoryLV) {
//
//                if (beanActHistoryLV.getStatus() == 1) {
//
//                    mHisGoods.addAll(beanActHistoryLV.getData().getList());
//                    mAdapter.notifyDataSetChanged();
//
//                    if (beanActHistoryLV.getData().getMore() == 1) {
//                        hasNextPage = true;
//                        mFootView.setToRefresh();
//                    } else {
//                        hasNextPage = false;
//                        mFootView.setFinished();
//                    }
//
//                } else {
//                    Toast.makeText(HistoryActivity.this, beanActHistoryLV.getInfo(), Toast.LENGTH_SHORT).show();
//                }

        }

    }
}
